<?php
class download_model extends CI_Model {

    function download_model() {
        parent::__construct();
    }

    function add($data) {
        foreach ($data as &$t) {
            $t = $this->db->escape_str($t);
        }
	$data['status']	= 0;
	$data['code'] = random_string('alnum', 8);
	$data['time'] = time();
        if ($this->db->insert('download', $data))
            return $this->db->insert_id();
        else
            return null;
    }

    function delete($id) {
        $this->db->where('id', $id);
        $this->db->delete('download');
        
        return true;
    }

    function update($id, $data) {
        $this->db->where('id', $id);
        $result = $this->db->get('download');
        if ($result->num_rows() == 0)
            return null;
        foreach ($data as &$t) {
            $t = $this->db->escape_str($t);
        }
        $this->db->where('id', $id);
        if ($this->db->update('download', $data))
            return true;
        else
            return null;
    }

    function get($order = 'id', $id=0, $limit = 0, $offset=0) {
        if (!is_numeric($id) || $id < 0)
            return null;

        if ($id == 0) {
            $this->db->order_by($order, 'DESC');
            if ($limit > 0)
                $this->db->limit($limit, $offset);
            $query = $this->db->get('download');
            if ($query->num_rows()>0)
            return $query->result();
            else return 0;
        }else {
            $this->db->where('id', $id);
            $query = $this->db->get('download');
            if ($query->num_rows()>0)
            return $query->first_row();
            else return 0;
        }
    }
    function get_by_code($code){
	$this->db->where('code',$code);
	$query = $this->db->get('download');
	if ($query->num_rows()>0)
	return $query->first_row();
	else return 0;
    }
    function download_finish($id){
	$this->db->where('id',$id);
	$query = $this->db->get('download');
	if ($query->num_rows()>0)
	{
	    $this->db->where('id',$id);
	    $this->db->update('download',array('status'=>1));
	    return true;
	}
	else return 0;
    }
}